package com.purchasing.system.config;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.purchasing.system.model.ERole;
import com.purchasing.system.model.Role;
import com.purchasing.system.model.User;
import com.purchasing.system.repository.RoleRepository;
import com.purchasing.system.repository.UserRepository;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private RoleRepository roleRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public void run(String... args) throws Exception {
        // 初始化角色
        initRoles();

        // 初始化管理员账号
        initAdminUser();
    }
    
    private void initRoles() {
        if (roleRepository.count() == 0) {
            Role employeeRole = new Role();
            employeeRole.setName(ERole.ROLE_EMPLOYEE);
            roleRepository.save(employeeRole);
            
            Role adminRole = new Role();
            adminRole.setName(ERole.ROLE_ADMIN);
            roleRepository.save(adminRole);
        }
    }
    
    private void initAdminUser() {
        //!userRepository.existsByUsername("admin")
//        if (!userRepository.existsByUsername("admin")) {
//            User admin = new User();
//            admin.setUsername("admin");
//            admin.setPassword(passwordEncoder.encode("admin123"));
//            admin.setEmail("admin@example.com");
//            admin.setName("系统管理员");
//            admin.setDepartment("信息技术部");
//
//            Set<Role> roles = new HashSet<>();
//            Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
//                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
//            roles.add(adminRole);
//            admin.setRoles(roles);
//
//            userRepository.save(admin);
//        }
        //!userRepository.existsByUsername("employee")
        if (!userRepository.existsByUsername("employee")) {
            User employee = new User();
            employee.setUsername("employee");
            employee.setPassword(passwordEncoder.encode("123456"));
            employee.setEmail("employee@example.com");
            employee.setName("测试员工");
            employee.setDepartment("市场部");
            
            Set<Role> roles = new HashSet<>();
            Role employeeRole = roleRepository.findByName(ERole.ROLE_EMPLOYEE)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(employeeRole);
            employee.setRoles(roles);
            
            userRepository.save(employee);
        }
    }
} 